<template>
    <el-upload
        :accept="accept"
        :action="action"
        :before-remove="beforeRemove"
        :before-upload="beforeUpload"
        :file-list="fileList"
        :headers="headers"
        :limit="limit"
        :multiple="limit > 1"
        :on-error="handleError"
        :on-exceed="handleExceed"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :show-file-list="true"
        class="upload-file"
        drag
        ref="uploader"
        v-bind="$attrs"
        v-if="drag"
    >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip" v-if="tips">{{ desc }}</div>
    </el-upload>
    <el-upload
        :accept="accept"
        :action="action"
        :before-remove="beforeRemove"
        :before-upload="beforeUpload"
        :file-list="fileList"
        :headers="headers"
        :limit="limit"
        :multiple="limit > 1"
        :on-error="handleError"
        :on-exceed="handleExceed"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :show-file-list="true"
        class="upload-file"
        ref="uploader"
        v-bind="$attrs"
        v-else
    >
        <el-button
            :size="btnProps.size || 'small'"
            :type="btnProps.type || 'primary'"
            v-bind="btnProps"
            :loading="isUploading"
            >{{ btnText }}</el-button
        >
        <div class="el-upload__tip" slot="tip" v-if="tips">{{ desc }}</div>
    </el-upload>
</template>

<script>
/*
  "orderAccessorys":[{
    "fileFormat": "string",//类型
    "fileSize": 0,
    "site": "string",
  }]
*/
import { mapGetters } from "vuex";
// import transferMixin from './transferMixin'
import { AliOssClient } from "../../lib/oss";
export default {
    name: "upload-file",
    // mixins: [transferMixin],
    props: {
        drag: {
            type: Boolean,
            default: false
        },
        url: {
            type: String,
            default: "/fileUploadxxx"
        },
        btnText: {
            type: String,
            default: "点击上传"
        },
        btnProps: {
            type: Object,
            default: () => ({})
        },
        tips: {
            type: Boolean,
            default: true
        },
        maxSize: {
            type: Number,
            default: 20
        },
        accept: {
            type: String,
            default: ".mp4,.ogg,.webm,.avi,.flv"
        },
        descText: {
            type: String,
            default: undefined
        },
        limit: {
            type: Number,
            default: 3
        },
        // 是否每次点击上传按钮清空列表
        clearable: {
            type: Boolean,
            default: false
        },
        value: {
            type: String,
            default: ""
        }
    },
    data() {
        return {
            fileList: [],
            dialogImageUrl: "",
            dialogVisible: false,
            isUploading: false
        };
    },
    watch: {
        value: {
            handler(val) {
                if (val) {
                    const arr = val.split(";");
                    this.fileList = arr.map(i => ({ url: i }));
                } else {
                    this.fileList = [];
                }
            }
        }
    },
    computed: {
        ...mapGetters({
            // token: "user/token"
        }),
        action() {
            return (
                process.env.VUE_APP_API_PREFIX_URL +
                process.env.VUE_APP_UPLOAD_URL +
                this.url
            );
        },
        // token
        headers() {
            return {
                token: `${this.$store.state.user.token}`
            };
        },
        desc() {
            return (
                this.descText ||
                `支持格式：${this.accept} ，单个文件不能超过${this.maxSize}MB，最多上传个数：${this.limit} 。`
            );
        }
    },
    methods: {
        handleChange(fileList) {
            this.fileList = fileList;
            console.log(fileList);
            this.$emit(
                "input",
                fileList.map(i => `${i.url},${i.name}`).join(";")
            );
        },

        handlePreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },

        handleExceed() {
            this.handleWarning(`只能选择 ${this.limit} 个文件`);
        },
        async beforeUpload(file) {
            // eslint-disable-next-line no-unused-vars
            console.log("file", file);
            const { size, type, name } = file;
            const ret = this.checkFileType(name) && this.checkFileSize(size);
            if (ret) {
                this.isUploading = true;
                try {
                    let res = await AliOssClient.upload(file);
                    console.log("res222: ", res);
                    this.isUploading = false;
                    this.$emit("input", res.url);
                    this.fileList.push({
                        url: res.url,
                        name: file.name
                    });
                    this.handleChange(this.fileList);
                    // return Promise.resolve(file);
                } catch (error) {
                    this.isUploading = false;
                }
            }
        },
        // eslint-disable-next-line no-unused-vars
        beforeRemove(file, fileList) {
            return true;
        },

        clearFiles() {
            this.$refs.uploader.clearFiles();
        },
        handleError() {
            this.isUploading = false;
            this.clearFiles();
            this.$message({
                type: "error",
                message: "上传失败！"
            });
        },
        async handleSuccess(res, file, fileList) {
            this.isUploading = false;

            // const arr = fileList.map(i => (i.response ? i.response.data : i.url));
            // const ret = arr.join(";");
            // this.$emit("change", ret);
            // this.$emit("input", ret);
        },
        handleRemove(file, fileList) {
            this.handleChange(fileList);
            // const ret = fileList.map(i => i.url).join(";");
            // this.$emit("change", ret);
            // this.$emit("input", ret);
        },
        checkFileType(name) {
            const t = name.substring(name.lastIndexOf("."));
            if (
                this.accept &&
                this.accept.split(",").filter(i => i.trim() === t).length === 0
            ) {
                this.handleWarning(`上传文件只能是 ${this.accept} 格式!`);
                return false;
            }
            return true;
        },
        checkFileSize(size) {
            if (size > 1024 * 1024 * this.maxSize) {
                this.handleWarning(`上传文件大小不能超过 ${this.maxSize} M!`);
                return false;
            }
            return true;
        }
    }
};
</script>
<style lang="scss" scoped>
.el-upload__tip {
    line-height: 1.2;
    margin: 10px 0 0;
    color: #e6a23c;
}
// 去掉upload 动画效果
/deep/.el-upload-list__item {
    transition: none !important;
}
</style>
